<?php

namespace App\Jobs;

use App\Models\Room;
use App\Repositories\RoomRepository;
use App\Services\LogService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ExpireRoomJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务超时时间（秒）
     */
    public int $timeout = 60;

    /**
     * 任务重试次数
     */
    public int $tries = 3;

    /**
     * Create a new job instance.
     */
    public function __construct(
        public int $roomId
    ) {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(RoomRepository $roomRepository, LogService $logService): void
    {
        $room = Room::find($this->roomId);
        
        if (!$room) {
            Log::warning("房间 {$this->roomId} 不存在，跳过过期处理");
            return;
        }

        // 检查房间是否仍然需要过期
        if ($room->status !== 'active') {
            Log::info("房间 {$room->room_id} 状态已不是 active，跳过过期处理");
            return;
        }

        if ($room->type === 'permanent') {
            Log::info("房间 {$room->room_id} 是永久房间，跳过过期处理");
            return;
        }

        try {
            // 标记房间为过期
            $roomRepository->markAsExpired($room->id);

            // 记录房间过期活动
            $logService->logRoomActivity('房间定时过期', $room, [
                'expired_at' => now(),
                'room_type' => $room->type,
                'expires_at' => $room->expires_at,
            ]);

            Log::info("房间 {$room->room_id} 已成功标记为过期");

        } catch (\Exception $e) {
            Log::error("处理房间 {$room->room_id} 过期时出错", [
                'error' => $e->getMessage(),
                'room_id' => $room->id,
            ]);
            
            throw $e;
        }
    }

    /**
     * 任务失败时的处理
     */
    public function failed(\Throwable $exception): void
    {
        Log::error('房间过期任务失败', [
            'room_id' => $this->roomId,
            'error' => $exception->getMessage(),
        ]);
    }
}
